/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.shop.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.shop.dao.GoodsDao;
import com.thinkgem.jeesite.modules.shop.entity.Goods;
import com.thinkgem.jeesite.modules.shop.entity.Product;
import com.thinkgem.jeesite.modules.shop.entity.Stock;

/**
 * 商品管理Service
 * @author xxs
 * @version 2016-03-21
 */
@Service
@Transactional(readOnly = true)
public class GoodsService extends CrudService<GoodsDao, Goods> {

	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private ProductService productService;
	@Autowired
	private StockService stockService;
	
	public Goods get(String id) {
		return super.get(id);
	}
	
	public List<Goods> findList(Goods goods) {
		return super.findList(goods);
	}
	
	public Page<Goods> findPage(Page<Goods> page, Goods goods) {
		return super.findPage(page, goods);
	}
	
	@Transactional(readOnly = false)
	public void save(Goods goods) {
		super.save(goods);
	}
	
	@Transactional(readOnly = false)
	public void save(Goods goods,Product product) {
		super.save(goods);
	}
	
	@Transactional(readOnly = false)
	public void save(Goods goods,List<Product> products) {
		super.save(goods);
		for (Product product : products) {
			product.setGoods(goods);
			productService.save(product);
			stockIn(product,"后台管理员");
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Goods goods) {
		super.delete(goods);
	}
	
	private void stockIn(Product product,String user) {
		if (product == null || product.getStock() == null || product.getStock() <= 0) {
			return;
		}
		Stock stock = new Stock();
		stock.setType("0");
		stock.setInQuantity(product.getStock());
		stock.setOutQuantity(0);
		stock.setStock(product.getStock());
		stock.setOperator(user);
		stock.setMemo(null);
		stock.setProduct(product);
		stockService.save(stock);
	}
	
}